import {createContext} from 'react'
import {action, observable} from 'mobx'
import {toConfirmBindDev, toWxScanAuth} from '@/utils/pageRedirect'
import Taro from '@tarojs/taro'
import {getParamByScan} from '@/utils/common'

class Scan {
  @observable loadingByloginScan: boolean = false
  @action.bound
  loginScan(address: string) {
    this.loadingByloginScan = true
    toWxScanAuth({address})
  }

  @action.bound
  handleScan(data?: {success?: Function}) {
    Taro.scanCode({
      success: async scan => {
        console.log('扫描二维码成功', scan)
        let {
          result //二维码包含的信息
        } = scan // 扫描二维码的回调

        // 判断二维码携带数据是否规范
        if (
          /https:\/\/d.lohand.com:10001\/weixin\/miniprogram\?/.test(result)
        ) {
          // 截取二维码路由携带参数
          let urlParamList = result
            .replace(/https:\/\/d.lohand.com:10001\/weixin\/miniprogram\?/, '')
            .split('&')
            .map(item => item.split('='))
          // 将参数数组组合成对象
          let query: {[key: string]: any} = {}
          urlParamList.map(item => {
            query[item[0]] = item[1]
          })

          console.log('二维码携带路由参数', urlParamList)
          // 判断路由参数，进而判断使用那个解析方式

          // 如果路由参数有qrcodeType（二维码类型）
          if (query.qrcodeType) {
            switch (query.qrcodeType) {
              case 'webScanLogin':
                if (query.webScanLogin_address) {
                  this.loginScan(query.webScanLogin_address)
                } else {
                  Taro.showToast({
                    title: '无效二维码03',
                    icon: 'error'
                  })
                }
                break
              case 'bindDev':
                let param = getParamByScan(result) // 线上版本二维码截取devGId
                if (param) {
                  toConfirmBindDev(param.devGId)
                }
                // this.bindDev({result, success: data?.success})
                break
              default:
                // 非指定类型的二维码，不进行处理
                Taro.showToast({
                  title: '无效二维码02',
                  icon: 'error'
                })
                break
            }
          } else {
            // 如果没有qrcodeType（二维码类型），代表是绑定设备的二维码(旧版本网页或者设备二维码)
            let param = getParamByScan(result) // 线上版本二维码截取devGId
            if (param) {
              toConfirmBindDev(param.devGId)
            }
          }
        } else {
          Taro.showToast({
            title: '无效二维码01',
            icon: 'error'
          })
        }
      },
      fail: err => {
        let {errMsg} = err
        if (errMsg.indexOf('cancel') === -1) {
          Taro.showModal({
            content: '扫描失败,请重新扫描'
          })
        }
        console.error(err)
      }
    })
  }
}

const scanStore = createContext(new Scan())
export default scanStore
